import numpy as np
#读取数据
def file2matrix(filename):
    fr = open(filename)
    arrayOLines = fr.readlines()
    numberOfLines = len(arrayOLines)
    returnMat = np.zeros((numberOfLines, 3))
    classLabelVector = []
    index = 0
    for line in arrayOLines:
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index, :] = list(map(float, listFromLine[0:3]))
        classLabelVector.append(listFromLine[-1])
        index += 1
    return returnMat, classLabelVector

#数据归一化
def autoNorm(dataSet):
    minVals = dataSet.min(0)
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = (dataSet - minVals) / ranges
    return normDataSet, ranges, minVals

#KNN分类
def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    sortedDistIndices = distances.argsort()
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndices[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
    return sortedClassCount[0][0]

datingDataMat, datingLabels = file2matrix('DatingTestSet.txt')
normMat, ranges, minVals = autoNorm(datingDataMat)
newData = np.array([10000, 10, 0.5])
normNewData = (newData - minVals) / ranges
k3_result = classify0(normNewData, normMat, datingLabels, 3)
k5_result = classify0(normNewData, normMat, datingLabels, 5)
print(f"当k=3时，预测类别为：{k3_result}")
print(f"当k=5时，预测类别为：{k5_result}")